<template>
  <BasicModal
    v-bind="$attrs"
    :width="modalWidth"
    @register="registerModal"
    :title="getTitle"
    @ok="handleOK"
  >
    <div>
      <BasicForm @register="chatregisterForm"> </BasicForm>
      <Card
        :tab-list="tabListTitle"
        v-bind="$attrs"
        :active-tab-key="activeKey"
        @tab-change="onTabChange"
      >
        <div>
          <Textarea
            v-if="activeKey == '0'"
            v-model:value="formattedLinks"
            placeholder="请输入用户账号  多条请用逗号分隔开"
            :rows="10"
          />
          <BasicTable v-if="activeKey == '1'" @register="registerTableUrl">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction
                  :actions="[
                    {
                      label: t('sys.script.details'),
                      tooltip: t('sys.script.details'),
                      onClick: handleView.bind(null, record),
                    },
                  ]"
                />
              </template>
            </template>
          </BasicTable>
        </div>
      </Card>
    </div>
    <DetailView @register="registerDetailView" @success="DetailViewSuccess"> </DetailView>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { useModal } from '@/components/Modal';
  import DetailView from './DetailView.vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getTaskDetailApi } from '@/api/demo/Task';
  import { Card, Textarea } from 'ant-design-vue';
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { chatAccountFormSchema } from './account.data';
  import { createTaskChat } from '@/api/demo/chat';
  import { taskMarketPageAPI } from '@/api/demo/InformationMatching';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  defineOptions({ name: 'AccountModal' });

  // 变量定义
  const activeKey = ref('0');
  const tabListTitle = [
    { key: '0', tab: '手动录入' },
    { key: '1', tab: '筛选' },
  ];
  const links = ref<string[]>([]);
  const formattedLinks = computed({
    get() {
      return links.value.join(',\n');
    },
    set(value) {
      links.value = value.split(',\n');
    },
  });
  const modalWidth = ref('60%');
  const isUpdate = ref(true);
  const rowId = ref('');
  const [registerDetailView, { openModal: openDetailView }] = useModal();
  const emit = defineEmits(['success']);

  // 方法定义
  const [chatregisterForm, { getFieldsValue }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: chatAccountFormSchema,
    showActionButtonGroup: false,
  });

  const columnsModelstab = ref([
    { title: 'id', dataIndex: 'id', width: 50 },
    { title: t('sys.informaionMatchaing.columns.title'), dataIndex: 'title', width: 50 },
    { title: t('sys.configuration.describe'), dataIndex: 'content', width: 50 },
    { title:  t('sys.informaionMatchaing.columns.district'), dataIndex: 'district', width: 50 },
    { title:  t('sys.informaionMatchaing.columns.audience'), dataIndex: 'audience', width: 50 },
    { title: t('sys.informaionMatchaing.columns.createTime'), dataIndex: 'createTime', width: 80 },
    {
      title: '匹配状态',
      dataIndex: 'status',
      width: 50,
      customRender: ({ record }: { record: Recordable }) => {
        if (record.status === 0) return t('sys.configuration.notStart');
        if (record.status === 1) return '执行中';
        return '执行成功';
      },
    },
    {
      title: t('sys.informaionMatchaing.columns.success'),
      dataIndex: 'success',
      width: 50,
      customRender: ({ record }: { record: Recordable }) => {
        const success = record.success ?? '-';
        const total = record.total ?? '-';
        return `${success}/${total}`;
      },
    },
  ]);

  const [registerTableUrl] = useTable({
    api: async (params) => {
      const result = (await taskMarketPageAPI(params)) as { items: any[]; total: number };
      return result;
    },
    rowKey: 'id',
    columns: columnsModelstab,
    actionColumn: { width: 80, title: t('sys.configuration.action'), dataIndex: 'action' },
    showIndexColumn: false,
    scroll: { y: 300 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('sys.configuration.add') : t('sys.configuration.edit')));

  async function handleOK() {
    const Data = {
      ...getFieldsValue(),
      userNos: links.value,
    };
    try {
      const data = await createTaskChat(Data);
      emit('success', data);
      closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function onTabChange(key) {
    activeKey.value = key;
  }

  function handleView(record: Recordable) {
    openDetailView(true, { record });
  }

  function DetailViewSuccess(record: Recordable) {
    links.value = record.urls;
  }
</script>
